package com.wzh.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.wzh.common.utils.R;
import com.wzh.goods.entity.ActivityEntity;
import com.wzh.goods.feign.ActivityFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.goods.dao.GoodsDao;
import com.wzh.goods.entity.GoodsEntity;
import com.wzh.goods.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private ActivityFeign activityFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R getBys(Long activityId, Long goodsId) {
        R r = new R();
        Object o = redisTemplate.boundHashOps("goods").get("good");
        if (o==null){
            System.out.println("查数据库");
            GoodsEntity goods = goodsDao.selectById(goodsId);
            redisTemplate.boundHashOps("goods").put("good",goods);
            r.put("goods",goods);
        }else {
            System.out.println("缓存命中");
            GoodsEntity goods= (GoodsEntity) redisTemplate.boundHashOps("goods").get("good");
            r.put("goods",goods);
        }
        R info = activityFeign.info(activityId);
        if (info.getCode()==0){
            Object activityToJSON = info.get("activity");
            String jsonString = JSON.toJSONString(activityToJSON);
            ActivityEntity activity = JSON.parseObject(jsonString, ActivityEntity.class);
            r.put("activity",activity).put("startTime",activity.getStartDate().getTime())
                    .put("endTime",activity.getEndDate().getTime());
        }
        return r;
    }

}